package com.mzj.saas.mservice.sys.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.UserLoginTypeEnum;
import com.mzj.saas.mservice.department.entity.Department;
import com.mzj.saas.mservice.department.entity.UserDepartmentRef;
import com.mzj.saas.mservice.department.repository.DepartmentRepository;
import com.mzj.saas.mservice.department.repository.UserDepartmentRefRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.roles.entity.UserRoleRef;
import com.mzj.saas.mservice.roles.repository.UserRoleRefRepository;
import com.mzj.saas.mservice.roles.service.RolesService;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.User;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.UserRepository;
import com.mzj.saas.mservice.sys.vo.AppUserVO;
import com.mzj.saas.mservice.sys.vo.PerUserVO;
import com.mzj.saas.mservice.sys.vo.UserCodeRequestVO;
import com.mzj.saas.mservice.sys.vo.WechatLoginVo;
import com.mzj.saas.mservice.token.service.TokenService;
import com.mzj.saas.redis.RedisService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

@Service
public class LoginService {
    private Logger LOG = LoggerFactory.getLogger(LoginService.class);
    public static final int HASH_INTERATIONS = 1024;

    @Autowired
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RolesService rolesService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserRoleRefRepository userRoleRefRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private UserDepartmentRefRepository userDepartmentRefRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;



    @Value("${officialAccount.appId}")
    private String officialAccountAppId;

    @Value("${officialAccount.secret}")
    private String officialAccountSecret;

    @Value("${officialAccount.openId.url}")
    private String officialAccountOpenIdUrl;


    /**
     * 登录(flag 1.PC登录 2.APP登录)
     *
     * @param vo 用户信息实体类
     * @return
     * @author shun
     * @date 2021年3月9日
     */
    public ResultBean<Map<String, Object>> login(PerUserVO vo) {
        //记录操作日志
        LOG.info("LoginService login UserVO = {}", JSON.toJSONString(vo));
        ResultBean<Map<String, Object>> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            //判断是否有手机号
            if (StringUtils.isEmpty(vo.getMobile())) {
                //记录操作日志
                LOG.warn(" Login mobile is null, mobile={}", vo.getMobile());
                //返回失败标识
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机号码为空");
                return resultBean;
            }
            if (vo.getFlag() == null) {
                LOG.warn(" Login flag is null, mobile={},flag={}", vo.getMobile(),
                        vo.getFlag());
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("标识不能为空");
                return resultBean;
            }
            User user  = userRepository.findByMobile(vo.getMobile());
            if (user == null) {
                LOG.warn(" Login user not found, mobile={}", vo.getMobile());
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("账户或密码错误");
                return resultBean;
            }

            Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();
            AppUserVO appVO = new AppUserVO();
            if (vo.getFlag() == 1) {
                // 验证企业用户表，查看用户是否存在
                appVO.setId(user.getId());
                appVO.setSalt(user.getSalt());
                appVO.setPassword(user.getPassword());
                appVO.setPhone(user.getMobile());
                appVO.setName(user.getName());
                appVO.setEnterpriseUserId(user.getId());
                appVO.setType(1);
                //新增 密码状态：1默认密码 2非默认密码 20230309 xiaolong
                appVO.setPasswordStatus(user.getPasswordStatus());
            } else {
                //修复bug
                user = userRepository.findByMobile(vo.getMobile());
                if (user == null) {
                    LOG.warn(" Login user not found, mobile={}", vo.getMobile());
                    resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                    resultBean.setMsg("账户或密码错误");
                    return resultBean;
                }
                // 验证app用户表，查看用户是否存在
                AppUser byPhone = appUserRepository.findByPhone(vo.getMobile());
                if (byPhone == null) {
                    // 验证企业用户表，查看用户是否存在
                    user = userRepository.findByMobile(vo.getMobile());
                    if (user != null) {
                        // 企业用户登录APP时同步账户，并自动生成普通用户id
                        String appUserId = "S" + KeyWorker.nextId();
                        appVO.setId(appUserId);
                        appVO.setEnterpriseUserId(user.getId());
                        appVO.setName(user.getName());
                        appVO.setSalt(user.getSalt());
                        appVO.setPassword(user.getPassword());
                        appVO.setPhone(user.getMobile());
                        appVO.setStatus(1);
                        appVO.setType(1);// 1.企业用户
                        appVO.setRegistrationTime(user.getCreateTime());
                        appVO.setCertificationStatus(0);// 默认未认证
                        byPhone = new AppUser();
                        BeanUtils.copyProperties(appVO, byPhone);
                        appUserRepository.save(byPhone);
                    }
                }
                if (user == null && byPhone == null) {
                    LOG.warn(" Login user not found, mobile={}", vo.getMobile());
                    resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                    resultBean.setMsg("账户或密码错误");
                    return resultBean;
                }
                appVO.setId(byPhone.getId());
                appVO.setSalt(byPhone.getSalt());
                appVO.setPassword(byPhone.getPassword());
                appVO.setPhone(byPhone.getPhone());
                appVO.setName(byPhone.getName());
                appVO.setEnterpriseUserId(byPhone.getEnterpriseUserId());

                // 普通用户登录
                if (byPhone != null && byPhone.getType() == 2) {
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }
            }

            // 验证密码
            byte[] inputHashPwd = Digests.sha1(vo.getPassword().getBytes(), Encodes.decodeHex(appVO.getSalt()),
                    HASH_INTERATIONS);
            String inputPwd = Encodes.encodeHex(inputHashPwd);

            if (!StringUtils.equals(inputPwd, appVO.getPassword())) {
                LOG.warn("inputPwd={}, dbPassword={}", inputPwd, appVO.getPassword());
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("密码错误 ");
                return resultBean;
            }

            // 未激活登录激活
            if (user != null && user.getStatus() == 0) {
                Short status = (short) 1;
                user.setStatus(status);
                userRepository.save(user);
            }
            // 管理员类型标识
            Long masterStatus = null;
            // 公司Id
            Long enterpriseId = null;
            String userId = null;
            if (appVO.getType() != null && appVO.getType() == 2) {
                userId = appVO.getId();
            } else {
                userId = appVO.getEnterpriseUserId();
            }
            User company = userRepository.findById(userId);
            if (company != null) {
                List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
                Long depId = null;
                if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
                    depId = userDepartmentRefList.get(0).getDepId();
                }
                // 查询一级机构id
                enterpriseId = userService.findCompanyByUserDepId(depId);
                if (enterpriseId == null) {
                    return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
                }
                appVO.setOrgId(enterpriseId);
                // 激活企业
                Optional<Department> existDepartment = departmentRepository.findById(enterpriseId);
                if (existDepartment != null) {
                    Department department = existDepartment.get();
                    department.setActivateStatus(1);
                    departmentRepository.save(department);
                }
                Boolean exist = userService.judgeManagerType(company.getId());
                if (exist) {
                    masterStatus = Long.valueOf(1);
                } else {
                    masterStatus = Long.valueOf(0);
                }
            }

            DepartmentHierarchy departmentHierarchy = departmentHierarchyRepository.findByOrgId(enterpriseId);
            if (departmentHierarchy != null) {
                if (departmentHierarchy.getStatus() == 0) {
                    return ResultBean.failedResultWithMsg("账号已停用，请联系管理人员");
                }
            }

            //判断密码是否是默认密码
            //if (vo.getPassword().equals("111111")) {
            //    appVO.setPasswordStatus(1);
            //} else {
            //    appVO.setPasswordStatus(2);
            //}
            // 生成token
            String accessToken = tokenService.authToken(appVO.getName(), appVO.getPassword(), appVO.getId(),
                    appVO.getPhone(), vo.getFlag(), masterStatus, enterpriseId, loginType, appVO.getEnterpriseUserId());
            resultMap.put("accessToken", accessToken);
            //查询企业名称
            //List<DepartmentHierarchy> departmentHierarchies = departmentHierarchyRepository.DepartmentId(vo.getMobile());
            //for (DepartmentHierarchy hierarchy : departmentHierarchies) {
            //    Long parentId = hierarchy.getParentId();
            //    if(parentId==0){
            //        appVO.setDepartmentName(departmentHierarchyRepository.DepartmentName(hierarchy.getId()));
            //    }else {
            //        appVO.setDepartmentName(departmentHierarchyRepository.DepartmentName(parentId));
            //    }
            //}
            Optional<Department> existDepartment = departmentRepository.findById(enterpriseId);
            appVO.setDepartmentName(existDepartment.get().getName());
            appVO.setPassword(null);
            appVO.setSalt(null);
            resultMap.put("user", appVO);
            return ResultBean.successfulResult(resultMap);
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
            return resultBean;
        }
    }

    /**
     * 验证码登录/注册
     * @param vo
     * @return
     */
    @Transactional
    public ResultBean<Object> codeLogin(UserCodeRequestVO vo) {
        LOG.info("LoginService codeLogin userCodeRequestVO = {}", vo);
        ResultBean<Object> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            if (vo == null) {
                return ResultBean.failedResultWithMsg("参数异常");
            }
            if (StringUtils.isEmpty(vo.getPhone())) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机号码为空");
                return resultBean;
            }
            if (StringUtils.isEmpty(vo.getCode())) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("验证码不能为空");
                return resultBean;
            }
            if (vo.getFlag() != 1){
                if (StringUtils.isEmpty(vo.getOpenId())) {
                    resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                    resultBean.setMsg("openId不能为空");
                    return resultBean;
                }
            }
            // 验证验证码
            String phone = redisService.getSmsCodeMobile(vo.getCode());
            if (StringUtils.isBlank(phone)) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("验证码不存在或已过期");
                return resultBean;
            }

            if (!vo.getPhone().equals(phone)) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机与验证码不匹配");
                return resultBean;
            }
            Integer loginType = null;

            AppUserVO appVO = new AppUserVO();
            if (vo.getFlag() == 1 ) {
                loginType = UserLoginTypeEnum.ENTERPRISE.getValue();
            } else if (vo.getFlag() == 2){
                loginType = UserLoginTypeEnum.CONSUMER.getValue();
            }else if (vo.getFlag() == 3){
                loginType = UserLoginTypeEnum.PROGRAM.getValue();
            }

            // 验证app用户表，查看用户是否存在
            AppUser byPhone = appUserRepository.findByPhoneAndTypeAndStatus(vo.getPhone(),loginType,1);
            if (byPhone == null) {
                LOG.warn(" Login user not found, mobile={}", vo.getPhone());
                //如果账户未找到，则自动注册
                if (vo.getPhone().equals(phone)) {
                    //获取盐值
                    byte[] salt = Digests.generateSalt(8);
                    String saltStr = Encodes.encodeHex(salt);
                    AppUser appUser = new AppUser();
                    appUser.setId("S" + KeyWorker.nextId());
                    appUser.setName(phone);
                    appUser.setPhone(phone);
                    if (vo.getFlag()!= 1){
                        appUser.setOpenId(vo.getOpenId());
                    }
                    if (vo.getFlag() == 2) {
                        appUser.setType(2);// app用户
                    } else {
                        appUser.setType(3);// 小程序用户
                    }
                    appUser.setCertificationStatus(0);
                    appUser.setStatus(1);
                    appUser.setSalt(saltStr);
                    appUser.setPassword(null);
                    appUser.setRegistrationTime(new Date());
                    appUser.setEnterpriseUserId(null);
                    AppUser save = appUserRepository.save(appUser);
                    if (save != null) {
                        // 查询普通用户角色
                        Long roleId = rolesService.getDefaultUserRoleId();
                        // 普通注册用户增加角色
                        UserRoleRef roleRef = new UserRoleRef();
                        roleRef.setRoleId(roleId);
                        roleRef.setUserId(appUser.getId());
                        userRoleRefRepository.save(roleRef);
                        LOG.info("UserService register success, roleId={}, roleRef={}", roleId, JSON.toJSON(roleRef));
                        byPhone = save;
                    } else {
                        return ResultBean.failedResultWithMsg("注册失败");
                    }
                } else {
                    return ResultBean.failedResultWithMsg("验证码已失效");
                }

                // 普通用户登录
                if (byPhone != null && byPhone.getType() == 2) {
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }

                appVO.setId(byPhone.getId());
                appVO.setSalt(byPhone.getSalt());
                appVO.setPassword(byPhone.getPassword());
                appVO.setPhone(byPhone.getPhone());
                appVO.setName(byPhone.getName());
                appVO.setEnterpriseUserId(byPhone.getEnterpriseUserId());


                // 生成token
                String accessToken = tokenService.authToken(appVO.getName(), appVO.getPassword(), appVO.getId(),
                        appVO.getPhone(), vo.getFlag(), null, null, loginType,
                        appVO.getEnterpriseUserId());
                resultMap.put("accessToken", accessToken);
                appVO.setPassword(null);
                appVO.setSalt(null);
                resultMap.put("user",appVO);
                return ResultBean.successfulResult(resultMap);
            }

            //更新openid
            if (vo.getFlag() != 1){
                byPhone.setOpenId(vo.getOpenId());
                byPhone = appUserRepository.save(byPhone);
            }

            Integer certificationStatus = byPhone.getCertificationStatus();


            // 生成token
            String accessToken = tokenService.authToken(byPhone.getName(), byPhone.getPassword(), byPhone.getId(),
                    byPhone.getPhone(), vo.getFlag(), null, null, loginType,
                    byPhone.getEnterpriseUserId(),certificationStatus);

            resultMap.put("accessToken", accessToken);
            byPhone.setPassword(null);
            byPhone.setSalt(null);
            //查询企业名称
            List<DepartmentHierarchy> departmentHierarchies = departmentHierarchyRepository.DepartmentId(vo.getPhone());
            for (DepartmentHierarchy departmentHierarchy : departmentHierarchies) {
                Long parentId = departmentHierarchy.getParentId();
                if(parentId==0){
                    byPhone.setDepartmentName(departmentHierarchyRepository.DepartmentName(departmentHierarchy.getId()));
                }else {
                    byPhone.setDepartmentName(departmentHierarchyRepository.DepartmentName(parentId));
                }
            }
            resultMap.put("user",byPhone);
            return ResultBean.successfulResult(resultMap);
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }
        return resultBean;
    }



    /*
     * 企业 验证码登录/注册
     */
    @Transactional
    public ResultBean<Object> orgCodeLogin(UserCodeRequestVO userCodeRequestVO) {
        LOG.info("LoginService codeLogin userCodeRequestVO = {}", userCodeRequestVO);
        ResultBean<Object> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            if (userCodeRequestVO == null) {
                return ResultBean.failedResultWithMsg("参数异常");
            }
            if (StringUtils.isEmpty(userCodeRequestVO.getPhone())) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机号码为空");
                return resultBean;
            }
            if (StringUtils.isEmpty(userCodeRequestVO.getCode())) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("验证码不能为空");
                return resultBean;
            }
            if (userCodeRequestVO.getFlag() == null) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("标识不能为空");
                return resultBean;
            }
            // 验证验证码
            String phone = redisService.getSmsCodeMobile(userCodeRequestVO.getCode());
            if (StringUtils.isBlank(phone)) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("验证码不存在或已过期");
                return resultBean;
            }
            // 验证企业用户表，查看用户是否存在
            User user = userRepository.findByMobile(userCodeRequestVO.getPhone());
            if (user == null) {
                LOG.warn(" Login user not found, mobile={}", userCodeRequestVO.getPhone());
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("账户未找到");
                return resultBean;
            }

            if (!userCodeRequestVO.getPhone().equals(phone)) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机与验证码不匹配");
                return resultBean;
            }

            AppUserVO appVO = new AppUserVO();

            Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();
            // 企业PC登录
            if (userCodeRequestVO.getFlag() == 1) {
                appVO.setId(user.getId());
                appVO.setSalt(user.getSalt());
                appVO.setPassword(user.getPassword());
                appVO.setPhone(user.getMobile());
                appVO.setName(user.getName());
                appVO.setEnterpriseUserId(user.getId());
                appVO.setType(1);
            } else {
                // 验证app用户表，查看用户是否存在
                AppUser byPhone = appUserRepository.findByPhone(userCodeRequestVO.getPhone());
                if (byPhone == null) {
                    // 验证企业用户表，查看用户是否存在
                    user = userRepository.findByMobile(userCodeRequestVO.getPhone());
                    if (user != null) {
                        // appVO.setId(user.getId());
                        appVO.setId("S" + KeyWorker.nextId());
                        appVO.setEnterpriseUserId(user.getId());
                        appVO.setName(user.getName());
                        appVO.setSalt(user.getSalt());
                        appVO.setPassword(user.getPassword());
                        appVO.setPhone(user.getMobile());
                        appVO.setStatus(Integer.valueOf(user.getStatus()));
                        appVO.setType(1);// 1.企业用户
                        appVO.setRegistrationTime(user.getCreateTime());
                        byPhone = new AppUser();
                        BeanUtils.copyProperties(appVO, byPhone);
                        appUserRepository.save(byPhone);
                    }
                }
                if (user == null && byPhone == null) {
                    LOG.warn(" Login user not found, mobile={}", userCodeRequestVO.getPhone());
                    //如果账户为找到，则自动注册
                    if (userCodeRequestVO.getPhone().equals(phone)) {
                        byte[] salt = Digests.generateSalt(8);
                        String saltStr = Encodes.encodeHex(salt);
                        AppUser appUser = new AppUser();
                        appUser.setId("S" + KeyWorker.nextId());
                        appUser.setName(phone);
                        appUser.setPhone(phone);
                        appUser.setType(2);// app用户
                        appUser.setCertificationStatus(0);
                        appUser.setStatus(1);
                        appUser.setSalt(saltStr);
                        appUser.setPassword(null);
                        appUser.setRegistrationTime(new Date());
                        appUser.setEnterpriseUserId(null);
                        AppUser save = appUserRepository.save(appUser);
                        if (save != null) {
                            // 查询普通用户角色
                            Long roleId = rolesService.getDefaultUserRoleId();
                            // 普通注册用户增加角色
                            UserRoleRef roleRef = new UserRoleRef();
                            roleRef.setRoleId(roleId);
                            roleRef.setUserId(appUser.getId());
                            userRoleRefRepository.save(roleRef);
                            LOG.info("UserService register success, roleId={}, roleRef={}", roleId, JSON.toJSON(roleRef));
                            byPhone=save;
                        } else {
                            return ResultBean.failedResultWithMsg("注册失败");
                        }
                    } else {
                        return ResultBean.failedResultWithMsg("验证码已失效");
                    }


                }

                // 普通用户登录
                if (byPhone != null && byPhone.getType() == 2) {
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }

                appVO.setId(byPhone.getId());
                appVO.setSalt(byPhone.getSalt());
                appVO.setPassword(byPhone.getPassword());
                appVO.setPhone(byPhone.getPhone());
                appVO.setName(byPhone.getName());
                appVO.setEnterpriseUserId(byPhone.getEnterpriseUserId());
            }

            // 管理员类型标识
            Long masterStatus = null;
            // 公司Id
            Long enterpriseId = null;
            String userId = null;
            if(appVO.getType() != null && appVO.getType() == 2){
                userId = appVO.getId();
            }else{
                userId = appVO.getEnterpriseUserId();
            }
            User company = userRepository.findById(userId);
            if (company != null) {
                List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
                Long depId = null;
                if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
                    depId = userDepartmentRefList.get(0).getDepId();
                }
                enterpriseId = userService.findCompanyByUserDepId(depId);
                if (enterpriseId == null) {
                    return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
                }
                Boolean exist = userService.judgeManagerType(company.getId());
                if (exist) {
                    masterStatus = Long.valueOf(1);
                } else {
                    masterStatus = Long.valueOf(0);
                }
            }

            // 生成token
            String accessToken = tokenService.authToken(appVO.getName(), appVO.getPassword(), appVO.getId(),
                    appVO.getPhone(), userCodeRequestVO.getFlag(), masterStatus, enterpriseId, loginType,
                    appVO.getEnterpriseUserId());
            // 未激活登录激活
            if (user != null) {
                if (StringUtils.isBlank(user.getPassword())) {
                    accessToken = null;
                } else {
                    if (user.getStatus() == 0) {
                        Short status = (short) 1;
                        user.setStatus(status);
                        userRepository.save(user);
                    }
                }
            }
            resultMap.put("accessToken", accessToken);
            //新增机构名称
            Optional<Department> existDepartment = departmentRepository.findById(enterpriseId);
            appVO.setDepartmentName(existDepartment.get().getName());
            appVO.setPassword(null);
            appVO.setSalt(null);
            resultMap.put("user", appVO);
            return ResultBean.successfulResult(resultMap);
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }
        return resultBean;
    }
    /**
     * 微信登录
     * @param openId
     * @return
     */
    public ResultBean<Object> weiChatLogin(String openId) {
        LOG.info("LoginService weiChatLogin openId = {}", openId);
        ResultBean<Object> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            AppUser existAppUser = appUserRepository.findByOpenId(openId);
            if (existAppUser != null) {
                AppUserVO appUserVO = new AppUserVO();
                BeanUtils.copyProperties(existAppUser, appUserVO);
                // User company = userRepository.findById(appUserVO.getId());

                String userId = null;
                if (existAppUser.getType() != null && existAppUser.getType() == 2) {
                    userId = appUserVO.getId();
                }

                Integer loginType = UserLoginTypeEnum.CONSUMER.getValue();
                // 生成token
                String accessToken = tokenService.authToken(appUserVO.getName(), appUserVO.getPassword(),
                        appUserVO.getId(), appUserVO.getPhone(), 2, null, null, loginType,
                        appUserVO.getEnterpriseUserId());
                resultMap.put("accessToken", accessToken);
                appUserVO.setPassword(null);
                appUserVO.setSalt(null);
                resultMap.put("user", appUserVO);
                resultBean.setResultData(resultMap);
            } else {




                return ResultBean.failedResultWithMsg("账户还未绑定");
            }
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }
        return resultBean;
    }

    /**
     * 微信登录
     * @param wechatLoginVo
     * @return
     */
    public ResultBean<Object> weiChatBindingLogin(WechatLoginVo wechatLoginVo) {
        LOG.info("---LoginService weiChatBindingLogin appUserVO={}", JSON.toJSONString(wechatLoginVo));
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        try {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
            if (wechatLoginVo == null || StringUtils.isBlank(wechatLoginVo.getPhone())) {
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                return result;
            }

            Integer loginType = UserLoginTypeEnum.PROGRAM.getValue();
            Integer flag = wechatLoginVo.getFlag();
            AppUser existAppUser = appUserRepository.findByPhoneAndTypeAndStatus(wechatLoginVo.getPhone(), flag, 1);

            if (StrUtil.isEmpty(wechatLoginVo.getOpenId())){
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                return result;
            }

            if (existAppUser != null && StringUtils.isNotEmpty(existAppUser.getOpenId()) &&
                    (existAppUser.getCertificationStatus() != null || existAppUser.getCertificationStatus() == 1)) {
                // 生成token
                String accessToken = tokenService.authToken(existAppUser.getName(), existAppUser.getPassword(), existAppUser.getId(),
                        existAppUser.getPhone(), flag, null, null, loginType, existAppUser.getEnterpriseUserId(), existAppUser.getCertificationStatus());
                resultMap.put("accessToken", accessToken);
                existAppUser.setPassword(null);
                existAppUser.setSalt(null);
                existAppUser.setOpenId(wechatLoginVo.getOpenId());
                existAppUser = appUserRepository.save(existAppUser);
                existAppUser.setCardNumber(null);
                resultMap.put("user", existAppUser);
                result.setResultData(resultMap);
            } else if (existAppUser != null && StringUtils.isNotEmpty(existAppUser.getOpenId()) &&
                    (existAppUser.getCertificationStatus() == null || existAppUser.getCertificationStatus() == 0)) {
                // 生成token
                String accessToken = tokenService.authToken(existAppUser.getName(), existAppUser.getPassword(), existAppUser.getId(),
                        existAppUser.getPhone(), flag, null, null, loginType, existAppUser.getEnterpriseUserId());
                resultMap.put("accessToken", accessToken);
                existAppUser.setPassword(null);
                existAppUser.setSalt(null);
                resultMap.put("user", existAppUser);
                result.setResultData(resultMap);
                existAppUser.setOpenId(wechatLoginVo.getOpenId());
                existAppUser = appUserRepository.save(existAppUser);
            } else if (existAppUser != null && StringUtils.isEmpty(existAppUser.getOpenId())) {
                //不验证密码
                //byte[] salt = Encodes.decodeHex(existAppUser.getSalt());

//				byte[] hashPassword = Digests.sha1(appUserVO.getPassword().getBytes(), salt, 1024);
//
//				String newPwd = Encodes.encodeHex(hashPassword);
//				if(!existAppUser.getPassword().equals(newPwd)){
//					result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
//					result.setMsg("密码与注册密码不符");
//					return result;
//				}
                existAppUser.setOpenId(wechatLoginVo.getOpenId());
                existAppUser.setNickName(wechatLoginVo.getNickName() == null ? null : wechatLoginVo.getNickName().getBytes());
                AppUser save = appUserRepository.save(existAppUser);

                AppUserVO userVO = new AppUserVO();
                BeanUtils.copyProperties(save, userVO);

                // 普通用户登录
                if (save.getType() != null && save.getType() == 2) {
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }
                existAppUser.setOpenId(wechatLoginVo.getOpenId());
                existAppUser = appUserRepository.save(existAppUser);

                // 生成token
                String accessToken = tokenService.authToken(userVO.getName(), userVO.getPassword(), userVO.getId(),
                        userVO.getPhone(), flag, null, null, loginType, existAppUser.getEnterpriseUserId());
                resultMap.put("accessToken", accessToken);
                userVO.setPassword(null);
                userVO.setSalt(null);
                resultMap.put("user", userVO);
                result.setResultData(resultMap);
            } else {
                AppUserVO userVO = new AppUserVO();
                byte[] salt = Digests.generateSalt(8);
                String saltStr = Encodes.encodeHex(salt);
                //byte[] hashPassword = Digests.sha1(appUserVO.getPassword().getBytes(), salt, 1024);
                //String password = Encodes.encodeHex(hashPassword);
                AppUser addAppUser = new AppUser();
                addAppUser.setId("S" + KeyWorker.nextId());
                addAppUser.setName(wechatLoginVo.getPhone());
                addAppUser.setPhone(wechatLoginVo.getPhone());
                addAppUser.setPassword(null);
                addAppUser.setSalt(saltStr);
                addAppUser.setOpenId(wechatLoginVo.getOpenId());
                addAppUser.setNickName(
                        wechatLoginVo.getNickName() == null ? null : wechatLoginVo.getNickName().getBytes());
                if (flag == 2){
                    addAppUser.setType(2);// app用户
                }else {
                    addAppUser.setType(3);// 小程序用户
                }
                addAppUser.setCertificationStatus(0);
                addAppUser.setStatus(1);
                addAppUser.setRegistrationTime(new Date());
                addAppUser.setEnterpriseUserId(null);
                AppUser save = appUserRepository.save(addAppUser);
                BeanUtils.copyProperties(save, userVO);
                if (flag == 2){
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }
                // 生成token
                String accessToken = tokenService.authToken(userVO.getName(), userVO.getPassword(),
                        userVO.getId(), userVO.getPhone(), flag, null, null, loginType, null);
                resultMap.put("accessToken", accessToken);
                userVO.setPassword(null);
                userVO.setSalt(null);
                resultMap.put("user", userVO);
                result.setResultData(resultMap);

                // 查询普通用户角色
                Long roleId = rolesService.getDefaultUserRoleId();
                // 普通注册用户增加角色
                UserRoleRef roleRef = new UserRoleRef();
                roleRef.setRoleId(roleId);
                roleRef.setUserId(save.getId());
                userRoleRefRepository.save(roleRef);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * app-ios 授权登录(未授权过)
     */
    public ResultBean<Object> iosBindingLogin(AppUserVO appUserVO) {
        LOG.info("---LoginService iosBindingLogin appUserVO={}", JSON.toJSONString(appUserVO));
        ResultBean<Object> result = new ResultBean<>();
        result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
        result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
        try {
            Map<String, Object> resultMap = new HashMap<String, Object>();
            result.setMsg(StatusCode.SUCCESS_CODE_10000.getErrorMsg());
            result.setCode(StatusCode.SUCCESS_CODE_10000.getErrorCode());
            if (appUserVO == null || StringUtils.isBlank(appUserVO.getPhone())) {
                result.setMsg(StatusCode.ERROR_CODE_10005.getErrorMsg());
                result.setCode(StatusCode.ERROR_CODE_10005.getErrorCode());
                return result;
            }
            if (StringUtils.isEmpty(appUserVO.getCode())) {
                result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                result.setMsg("验证码不能为空");
                return result;
            }


            // 验证验证码
            String phone = redisService.getSmsCodeMobile(appUserVO.getCode());
            if (StringUtils.isBlank(phone)) {
                return ResultBean.failedResultWithMsg("验证码未找到或已过期");
            }

            if (!appUserVO.getPhone().equals(phone)) {
                return ResultBean.failedResultWithMsg("手机与验证码不匹配");
            }

            Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();

            AppUser existAppUser = appUserRepository.findByPhone(appUserVO.getPhone());
            if (existAppUser != null && StringUtils.isNotEmpty(existAppUser.getOpenId())) {
                return ResultBean.failedResultWithMsg("该手机号已被绑定");
            } else if (existAppUser != null && StringUtils.isEmpty(existAppUser.getOpenId())) {
                //不验证密码
//				byte[] salt = Encodes.decodeHex(existAppUser.getSalt());
//				byte[] hashPassword = Digests.sha1(appUserVO.getPassword().getBytes(), salt, 1024);
//
//				String newPwd = Encodes.encodeHex(hashPassword);
//				if(!existAppUser.getPassword().equals(newPwd)){
//					result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
//					result.setMsg("密码与注册密码不符");
//					return result;
//				}
                //existAppUser.setIosOpenId(appUserVO.getIosOpenId());
                existAppUser.setNickName(appUserVO.getNickName() == null ? null : appUserVO.getNickName().getBytes());
                AppUser save = appUserRepository.save(existAppUser);
                // 管理员类型标识
                Long masterStatus = null;
                // 公司Id
                Long enterpriseId = null;
                // 判断用户所属类型
                if (save.getType() != null && save.getType() == 1) {
                    String userId = null;
                    if (save.getType() == 2) {
                        userId = save.getId();
                    } else {
                        userId = save.getEnterpriseUserId();
                    }
                    User user = userRepository.findById(userId);
                    if (user != null) {
                        List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository
                                .findByUserId(userId);
                        Long depId = null;
                        if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
                            depId = userDepartmentRefList.get(0).getDepId();
                        }
                        enterpriseId = userService.findCompanyByUserDepId(depId);
                        if (enterpriseId == null) {
                            return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
                        }
                        Boolean exist = userService.judgeManagerType(user.getId());
                        if (exist) {
                            masterStatus = Long.valueOf(1);
                        } else {
                            masterStatus = Long.valueOf(0);
                        }
                    }
                }
                AppUserVO userVO = new AppUserVO();
                BeanUtils.copyProperties(save, userVO);

                // 普通用户登录
                if (save.getType() != null && save.getType() == 2) {
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }

                // 生成token
                String accessToken = tokenService.authToken(userVO.getName(), userVO.getPassword(), userVO.getId(),
                        userVO.getPhone(), 2, masterStatus, enterpriseId, loginType, appUserVO.getEnterpriseUserId());
                resultMap.put("accessToken", accessToken);
                userVO.setPassword(null);
                userVO.setSalt(null);
                resultMap.put("user", userVO);
                result.setResultData(resultMap);
            } else {
                AppUserVO userVO = new AppUserVO();
                byte[] salt = Digests.generateSalt(8);
                String saltStr = Encodes.encodeHex(salt);
                //byte[] hashPassword = Digests.sha1(appUserVO.getPassword().getBytes(), salt, 1024);
                //String password = Encodes.encodeHex(hashPassword);
                AppUser addAppUser = new AppUser();
                addAppUser.setId("S" + KeyWorker.nextId());
                addAppUser.setName(appUserVO.getPhone());
                addAppUser.setPhone(appUserVO.getPhone());
                addAppUser.setPassword(null);
                addAppUser.setSalt(saltStr);
                //addAppUser.setIosOpenId(appUserVO.getIosOpenId());
                addAppUser.setNickName(
                        appUserVO.getNickName() == null ? null : appUserVO.getNickName().getBytes());
                addAppUser.setType(2);// app用户
                addAppUser.setCertificationStatus(0);
                addAppUser.setStatus(1);
                addAppUser.setRegistrationTime(new Date());
                addAppUser.setEnterpriseUserId(null);
                AppUser save = appUserRepository.save(addAppUser);
                BeanUtils.copyProperties(save, userVO);

                loginType = UserLoginTypeEnum.CONSUMER.getValue();
                // 生成token
                String accessToken = tokenService.authToken(userVO.getName(), userVO.getPassword(),
                        userVO.getId(), userVO.getPhone(), 2, null, null, loginType, null);
                resultMap.put("accessToken", accessToken);
                userVO.setPassword(null);
                userVO.setSalt(null);
                resultMap.put("user", userVO);
                result.setResultData(resultMap);

                // 查询普通用户角色
                Long roleId = rolesService.getDefaultUserRoleId();
                // 普通注册用户增加角色
                UserRoleRef roleRef = new UserRoleRef();
                roleRef.setRoleId(roleId);
                roleRef.setUserId(save.getId());
                userRoleRefRepository.save(roleRef);
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            result.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            result.setMsg(e.getMessage());
        }
        return result;
    }

    /*
     * ios-app授权登录
     */
    public ResultBean<Object> iosLogin(String iosOpenId) {
        LOG.info("LoginService iosLogin iosOpenId = {}", iosOpenId);
        ResultBean<Object> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();
            AppUser existAppUser = appUserRepository.findByIosOpenId(iosOpenId);
            if (existAppUser != null) {
                AppUserVO appUserVO = new AppUserVO();
                BeanUtils.copyProperties(existAppUser, appUserVO);
                // 管理员类型标识
                Long masterStatus = null;
                // 公司Id
                Long enterpriseId = null;
                // User company = userRepository.findById(appUserVO.getId());

                String userId = null;
                if (existAppUser.getType() != null && existAppUser.getType() == 2) {
                    userId = appUserVO.getId();
                } else {
                    userId = appUserVO.getEnterpriseUserId();
                }

                User company = userRepository.findById(userId);
                if (company != null) {
                    List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
                    Long depId = null;
                    if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
                        depId = userDepartmentRefList.get(0).getDepId();
                    }
                    enterpriseId = userService.findCompanyByUserDepId(depId);
                    if (enterpriseId == null) {
                        return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
                    }
                    // 激活企业
                    Optional<Department> existDepartment = departmentRepository.findById(enterpriseId);
                    if (existDepartment != null) {
                        Department department = existDepartment.get();
                        department.setActivateStatus(1);
                        departmentRepository.save(department);
                    }
                    Boolean exist = userService.judgeManagerType(company.getId());
                    if (exist) {
                        masterStatus = Long.valueOf(1);
                    } else {
                        masterStatus = Long.valueOf(0);
                    }
                }
                Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();
                // 普通用户登录
                if (existAppUser.getType() != null && existAppUser.getType() == 2) {
                    loginType = UserLoginTypeEnum.CONSUMER.getValue();
                }
                // 生成token
                String accessToken = tokenService.authToken(appUserVO.getName(), appUserVO.getPassword(),
                        appUserVO.getId(), appUserVO.getPhone(), 2, masterStatus, enterpriseId, loginType,
                        appUserVO.getEnterpriseUserId());
                resultMap.put("accessToken", accessToken);
                appUserVO.setPassword(null);
                appUserVO.setSalt(null);
                resultMap.put("user", appUserVO);
                resultBean.setResultData(resultMap);
            } else {
                return ResultBean.failedResultWithMsg("账户还未绑定");
            }
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }
        return resultBean;
    }

    /**
     * 本机号码一键登录
     *
     * @return
     */
    @Transactional
    public ResultBean<Object> clickLogin(AppUserVO vo) {
        LOG.info("LoginService codeLogin vo = {}", JSONObject.toJSON(vo));
        ResultBean<Object> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();

            if (StringUtils.isEmpty(vo.getPhone())) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机号码为空");
                return resultBean;
            }

            String phone = vo.getPhone();

            AppUserVO appVO = new AppUserVO();
            User user = null;
            Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();

            // 验证app用户表，查看用户是否存在
            AppUser byPhone = appUserRepository.findByPhone(phone);
            if (byPhone == null) {
                // 验证企业用户表，查看用户是否存在
                user = userRepository.findByMobile(phone);
                if (user != null) {
                    // appVO.setId(user.getId());
                    appVO.setId("S" + KeyWorker.nextId());
                    appVO.setEnterpriseUserId(user.getId());
                    appVO.setName(user.getName());
                    appVO.setSalt(user.getSalt());
                    appVO.setPassword(user.getPassword());
                    appVO.setPhone(user.getMobile());
                    appVO.setStatus(Integer.valueOf(user.getStatus()));
                    appVO.setType(1);// 1.企业用户
                    appVO.setRegistrationTime(user.getCreateTime());
                    byPhone = new AppUser();
                    BeanUtils.copyProperties(appVO, byPhone);
                    appUserRepository.save(byPhone);
                }
            }
            if (user == null && byPhone == null) {
                LOG.warn(" Login user not found, mobile={}", phone);
                //如果账户为找到，则自动注册
                byte[] salt = Digests.generateSalt(8);
                String saltStr = Encodes.encodeHex(salt);
                AppUser appUser = new AppUser();
                appUser.setId("S" + KeyWorker.nextId());
                appUser.setName(phone);
                appUser.setPhone(phone);
                appUser.setType(2);// app用户
                appUser.setCertificationStatus(0);
                appUser.setStatus(1);
                appUser.setSalt(saltStr);
                appUser.setPassword(null);
                appUser.setRegistrationTime(new Date());
                appUser.setEnterpriseUserId(null);
                AppUser save = appUserRepository.save(appUser);
                if (save != null) {
                    // 查询普通用户角色
                    Long roleId = rolesService.getDefaultUserRoleId();
                    // 普通注册用户增加角色
                    UserRoleRef roleRef = new UserRoleRef();
                    roleRef.setRoleId(roleId);
                    roleRef.setUserId(appUser.getId());
                    userRoleRefRepository.save(roleRef);
                    LOG.info("UserService register success, roleId={}, roleRef={}", roleId, JSON.toJSON(roleRef));
                    byPhone = save;
                } else {
                    return ResultBean.failedResultWithMsg("注册失败");
                }


//					resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
//					resultBean.setMsg("账户未找到");
//					return resultBean;
            }

            // 普通用户登录
            if (byPhone != null && byPhone.getType() == 2) {
                loginType = UserLoginTypeEnum.CONSUMER.getValue();
            }

            appVO.setId(byPhone.getId());
            appVO.setSalt(byPhone.getSalt());
            appVO.setPassword(byPhone.getPassword());
            appVO.setPhone(byPhone.getPhone());
            appVO.setName(byPhone.getName());
            appVO.setEnterpriseUserId(byPhone.getEnterpriseUserId());


            // 管理员类型标识
            Long masterStatus = null;
            // 公司Id
            Long enterpriseId = null;
            String userId = null;
            if (appVO.getType() != null && appVO.getType() == 2) {
                userId = appVO.getId();
            } else {
                userId = appVO.getEnterpriseUserId();
            }
            User company = userRepository.findById(userId);
            if (company != null) {
                List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
                Long depId = null;
                if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
                    depId = userDepartmentRefList.get(0).getDepId();
                }
                enterpriseId = userService.findCompanyByUserDepId(depId);
                if (enterpriseId == null) {
                    return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
                }
                Boolean exist = userService.judgeManagerType(company.getId());
                if (exist) {
                    masterStatus = Long.valueOf(1);
                } else {
                    masterStatus = Long.valueOf(0);
                }
            }

            // 生成token
            String accessToken = tokenService.authToken(appVO.getName(), appVO.getPassword(), appVO.getId(),
                    appVO.getPhone(), 1, masterStatus, enterpriseId, loginType,
                    appVO.getEnterpriseUserId());
            // 未激活登录激活
            if (user != null) {
                if (StringUtils.isBlank(user.getPassword())) {
                    accessToken = null;
                } else {
                    if (user.getStatus() == 0) {
                        Short status = (short) 1;
                        user.setStatus(status);
                        userRepository.save(user);
                    }
                }
            }
            resultMap.put("accessToken", accessToken);
            appVO.setPassword(null);
            appVO.setSalt(null);
            //查询企业名称
            List<DepartmentHierarchy> departmentHierarchies = departmentHierarchyRepository.DepartmentId(vo.getPhone());
            for (DepartmentHierarchy departmentHierarchy : departmentHierarchies) {
                Long parentId = departmentHierarchy.getParentId();
                if (parentId == 0) {
                    appVO.setDepartmentName(departmentHierarchyRepository.DepartmentName(departmentHierarchy.getId()));
                    resultMap.put("departmentName", departmentHierarchyRepository.DepartmentName(departmentHierarchy.getId()));
                } else {
                    appVO.setDepartmentName(departmentHierarchyRepository.DepartmentName(parentId));
                }
            }
            resultMap.put("user", appVO);
            return ResultBean.successfulResult(resultMap);
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }
        return resultBean;
    }


    /**
     * 本机号码一键登录
     *
     * @return
     */
    @Transactional
    public ResultBean<Object> clickLoginV3(AppUserVO vo) {
        LOG.info("LoginService codeLogin vo = {}", JSONObject.toJSON(vo));
        ResultBean<Object> resultBean = new ResultBean<>();
        try {
            Map<String, Object> resultMap = new HashMap<>();

            if (StringUtils.isEmpty(vo.getPhone())) {
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("手机号码为空");
                return resultBean;
            }

            String phone = vo.getPhone();

            AppUserVO appVO = new AppUserVO();
            User user = null;
            Integer loginType = UserLoginTypeEnum.ENTERPRISE.getValue();

            // 验证企业用户表，查看用户是否存在
            user = userRepository.findByMobile(phone);
            if (user == null){
                resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                resultBean.setMsg("当前账号无权限");
                return resultBean;
            }
            appVO.setId(user.getId());
            appVO.setSalt(user.getSalt());
            appVO.setPassword(user.getPassword());
            appVO.setPhone(user.getMobile());
            appVO.setName(user.getName());
            appVO.setEnterpriseUserId(user.getId());
            appVO.setType(1);
            //新增 密码状态：1默认密码 2非默认密码 20230309 xiaolong
            appVO.setPasswordStatus(user.getPasswordStatus());


            // 管理员类型标识
            Long masterStatus = null;
            // 公司Id
            Long enterpriseId = null;
            String userId = null;
            if (appVO.getType() != null && appVO.getType() == 2) {
                userId = appVO.getId();
            } else {
                userId = appVO.getEnterpriseUserId();
            }
            User company = userRepository.findById(userId);
            if (company != null) {
                List<UserDepartmentRef> userDepartmentRefList = userDepartmentRefRepository.findByUserId(userId);
                Long depId = null;
                if (userDepartmentRefList != null && userDepartmentRefList.size() != 0) {
                    depId = userDepartmentRefList.get(0).getDepId();
                }
                enterpriseId = userService.findCompanyByUserDepId(depId);
                if (enterpriseId == null) {
                    return ResultBean.failedResultWithMsg("账号信息有误，公司不存在");
                }
                appVO.setOrgId(enterpriseId);
                // 激活企业
                Optional<Department> existDepartment = departmentRepository.findById(enterpriseId);
                if (existDepartment != null) {
                    Department department = existDepartment.get();
                    department.setActivateStatus(1);
                    departmentRepository.save(department);
                }
                Boolean exist = userService.judgeManagerType(company.getId());
                if (exist) {
                    masterStatus = Long.valueOf(1);
                } else {
                    masterStatus = Long.valueOf(0);
                }
            }

            DepartmentHierarchy orgId = departmentHierarchyRepository.findByOrgId(enterpriseId);
            if (orgId != null) {
                if (orgId.getStatus() == 0) {
                    return ResultBean.failedResultWithMsg("账号已停用，请联系管理人员");
                }
            }

            // 生成token
            String accessToken = tokenService.authToken(appVO.getName(), appVO.getPassword(), appVO.getId(),
                    appVO.getPhone(), 1, masterStatus, enterpriseId, loginType,
                    appVO.getEnterpriseUserId());
            // 未激活登录激活
            if (user != null) {
                if (StringUtils.isBlank(user.getPassword())) {
                    accessToken = null;
                } else {
                    if (user.getStatus() == 0) {
                        Short status = (short) 1;
                        user.setStatus(status);
                        userRepository.save(user);
                    }
                }
            }
            resultMap.put("accessToken", accessToken);
            appVO.setPassword(null);
            appVO.setSalt(null);
            //查询企业名称
            List<DepartmentHierarchy> departmentHierarchies = departmentHierarchyRepository.DepartmentId(vo.getPhone());
            for (DepartmentHierarchy departmentHierarchy : departmentHierarchies) {
                Long parentId = departmentHierarchy.getParentId();
                if(parentId==0){
                    appVO.setDepartmentName(departmentHierarchyRepository.DepartmentName(departmentHierarchy.getId())); resultMap.put("departmentName",departmentHierarchyRepository.DepartmentName(departmentHierarchy.getId()));
                }else {
                    appVO.setDepartmentName(departmentHierarchyRepository.DepartmentName(parentId));
                }
            }
            resultMap.put("user", appVO);
            return ResultBean.successfulResult(resultMap);
        } catch (Exception e) {
            LOG.error("LoginService login Exception = {}", e);
            resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
            resultBean.setMsg(StatusCode.ERROR_CODE_10001.getErrorMsg());
        }
        return resultBean;
    }


    /**
     * <a>https://blog.csdn.net/xiaolinlife/article/details/132269330</a>
     * @param code
     * @return
     */
    public ResultBean<Object> gainOpenId(String code) {
        if (StrUtil.isBlank(code)){
            return ResultBean.failedResultWithMsg("code不能为空");
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid",officialAccountAppId);
        paramMap.put("secret",officialAccountSecret);
        paramMap.put("grant_type","authorization_code");
        paramMap.put("code",code);
        String result = HttpUtil.get(officialAccountOpenIdUrl, paramMap);
        Map map = JSON.parseObject(result, Map.class);
        if (CollectionUtil.isNotEmpty(map)){
            Object openid = map.get("openid");
            if (openid != null){
                return  ResultBean.successfulResult(openid);
            }
        }
        return   ResultBean.failedResultWithMsg("获取openid失败");
    }
}
